//
//  StudioPlayerTool.m
//  AnotherMediaTool
//
//  Created by fh on 2018/9/10.
//  Copyright © 2018年 fh. All rights reserved.
//

#import "StudioPreviewTool.h"
#import "PhotoPreview.h"

@interface StudioPreviewTool () <AVAudioPlayerDelegate> {
    /// 私有当前音频路径
    NSString *_innerCurAudioPath;
}
/** 视频路径 */
@property (nonatomic, strong) NSURL *videoUrl;
/** 视频播放器 */
@property (nonatomic, strong) AVPlayer *videoPlayer;
/** 音频播放器 */
@property (nonatomic, strong) AVAudioPlayer *audioPlayer;
/** 照片预览视图 */
@property (nonatomic, strong) PhotoPreview *photoPreview;
@end

@implementation StudioPreviewTool

#pragma mark - Life
- (void)dealloc {
#ifdef DEBUG
    NSLog(@"%@ 释放了",[self class]);
#endif
}

#pragma mark - Public
/**
 预览图片:模仿系统相机预览
 
 @param image 预览的图片
 @param previewSuperView 预览图的父视图
 @param previewSuperViewFrame 预览图的父视图frame
 @param retakeClickBlock 重拍回调
 @param usePhotoClickBlock 选中回调
 */
- (void)previewPhotoWithImage:(UIImage *)image previewSuperView:(UIView *)previewSuperView previewSuperViewFrame:(CGRect)previewSuperViewFrame retakeClickBlock:(void (^)(void))retakeClickBlock usePhotoClickBlock:(void (^)(UIImage *))usePhotoClickBlock {

    self.photoPreview.frame = previewSuperViewFrame;
    [previewSuperView addSubview:self.photoPreview];
    self.photoPreview.imgPreview.image = image;
    
    __weak typeof(self) weakSelf = self;
    self.photoPreview.useImgButtonClickBlock = ^(UIButton *button) {
        if (usePhotoClickBlock) {
            usePhotoClickBlock(image);
        }
        [weakSelf.photoPreview removeFromSuperview];
        weakSelf.photoPreview = nil;
    };
    self.photoPreview.retakeButtonClickBlock = ^(UIButton *button) {
        [weakSelf.photoPreview removeFromSuperview];
        weakSelf.photoPreview = nil;
        if (retakeClickBlock) {
            retakeClickBlock();
        }
    };
    
}

/**
 创建系统视频播放控制器
 
 @param url 视频URL
 @return 系统播放器
 */
+ (AVPlayerViewController *)createSystemPlayerViewControllerWithURL:(NSURL *)url {
    if (!url) {
        return nil;
    }
    AVPlayer *avPlayer = [AVPlayer playerWithURL:url];
    // player的控制器对象
    AVPlayerViewController *playerViewController = [[AVPlayerViewController alloc] init];
    // 控制器的player播放器
    playerViewController.player = avPlayer;
    // 试图的填充模式
    playerViewController.videoGravity = AVLayerVideoGravityResizeAspect;
    // 是否显示播放控制条
    playerViewController.showsPlaybackControls = YES;
    return playerViewController;
}

/**
 预览视频:用于录制完成视频之后预览视频,没有进度没有视频信息
 
 @param videoUrl 视频URL
 @param preview 预览图
 @param previewFrame 预览图尺寸
 */
- (void)previewVideoWithoutRelevantInfoWithVideoURL:(NSURL *)videoUrl preview:(UIView *)preview previewFrame:(CGRect)previewFrame {
    
    ///*
    self.videoUrl = videoUrl;
    AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:self.videoUrl];
    self.videoPlayer = [AVPlayer playerWithPlayerItem:playerItem];

    AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.videoPlayer];
    playerLayer.frame = previewFrame;
    [preview.layer addSublayer:playerLayer];

    if (self.repeatPreviewVideo) {
       [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackFinished:) name:AVPlayerItemDidPlayToEndTimeNotification object:self.videoPlayer.currentItem];
    }

    if (self.videoPlayer.rate == 0) {
        [self.videoPlayer play];
    }
    //*/
    
    /*
    self.videoPreview.frame = previewFrame;
    [preview addSubview:self.videoPreview];
    
//    return;
    __weak typeof(self) weakSelf = self;
    self.videoPreview.sureButtonClickBlock = ^(UIButton *button) {
//        if (usePhotoClickBlock) {
//            usePhotoClickBlock(image);
//        }
        [weakSelf.videoPlayer pause];
        [weakSelf.videoPreview removeFromSuperview];
        weakSelf.videoPreview = nil;
        
    };
    self.videoPreview.cancleButtonClickBlock = ^(UIButton *button) {
        [weakSelf.videoPlayer pause];
        [weakSelf.videoPreview removeFromSuperview];
        weakSelf.videoPreview = nil;
//        if (retakeClickBlock) {
//            retakeClickBlock();
//        }
        
    };
    
    self.videoUrl = videoUrl;
    AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:self.videoUrl];
    self.videoPlayer = [AVPlayer playerWithPlayerItem:playerItem];
    
    AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.videoPlayer];
    playerLayer.frame = self.videoPreview.videoPreview.bounds;
    [self.videoPreview.videoPreview.layer addSublayer:playerLayer];
    
    if (self.repeatPreviewVideo) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackFinished:) name:AVPlayerItemDidPlayToEndTimeNotification object:self.videoPlayer.currentItem];
    }
    
    if (self.videoPlayer.rate == 0) {
        [self.videoPlayer play];
    }
    //*/
    
}

/**
 预听录音
 
 @param audioPath 录音URL
 */
- (void)preListeningAudioWithoutRelevantInfoWithAudioPath:(NSString *)audioPath {
    _innerCurAudioPath = audioPath;
    if (!self.audioPlayer) {
        AVAudioSession *session = [AVAudioSession sharedInstance];
        NSError *error = nil;
        [session setCategory:AVAudioSessionCategoryPlayback error:&error];
        if(error) {
#ifdef DEBUG
            NSLog(@"播放错误说明: %@", [error description]);
#endif
        }
        NSURL *url;
        if (audioPath) {
            url = [NSURL fileURLWithPath:audioPath];;
        }
        if (!url) {
            return;
        }
        self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
        self.audioPlayer.delegate = self;
    }
    [self.audioPlayer prepareToPlay];
    [self.audioPlayer play];
}

#pragma mark - Private
/**
 暂停播放
 */
- (void)pauseAudioPlaying {
    [self.audioPlayer pause];
}

/**
 停止播放
 */
- (void)stopAudioPlaying {
    [self.audioPlayer stop];
    self.audioPlayer = nil;
}

#pragma mark - AVAudioPlayerDelegate
//播放结束的代理方法
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
    self.audioPlayer = nil;
    if (self.repeatPreListeningAudio) {
        [self preListeningAudioWithoutRelevantInfoWithAudioPath:_innerCurAudioPath];
    }
}

#pragma mark - Notification
/**
 播放结束通知方法
 
 @param notification 播放结束通知
 */
- (void)playbackFinished:(NSNotification *)notification {
    [self.videoPlayer seekToTime:CMTimeMake(0, 1)];
    [self.videoPlayer play];
}

#pragma mark - Setter and getter
- (PhotoPreview *)photoPreview {
    if (!_photoPreview) {
        _photoPreview = [[PhotoPreview alloc] init];
    }
    return _photoPreview;
}

@end








